#include "ScreenCapture.h"
#include "common.h"

CScreenCapture::CScreenCapture(IOScreenCaptureNotify *pNotify)
:m_pNotify(pNotify)
,m_bExit(false)
,m_tStatus(notcapture_status)
,m_pData(NULL)
,m_bInit(false)
{
	Init();

	StartThread();
}

CScreenCapture::~CScreenCapture(void)
{
	m_bExit = true;

	WaitForStop();

	if (m_bInit)
	{
		DeleteObject(m_hBitmap);
		DeleteDC(m_hMenDc);
	}

	if (m_pData)
	{
		delete [] m_pData;
		m_pData = NULL;
	}
}

void CScreenCapture::StartCapture(void)
{
	m_tStatus = capture_status;
}

void CScreenCapture::StopCapture(void)
{
	m_tStatus = notcapture_status;
}

void CScreenCapture::ThreadProcMain(void)
{
	while (!m_bExit)
	{
		if (m_tStatus == capture_status)
		{
			if (m_bInit)
				CaptureScreen();
		}

		my_sleep(50);
	}
}

void CScreenCapture::GetResolution(void)
{
	m_tParam.nWidth = GetSystemMetrics(SM_CXSCREEN);
	m_tParam.nHeigth = GetSystemMetrics(SM_CYSCREEN);

	/*m_tParam.nWidth -= m_tParam.nWidth % 16;
	m_tParam.nHeigth -= m_tParam.nHeigth % 16;*/
}

bool CScreenCapture::Init(void)
{
	HDC dc = GetDC(NULL);

	m_hMenDc = CreateCompatibleDC(dc);

	GetResolution();

	BITMAPINFOHEADER bmif;
	bmif.biSize          = sizeof(BITMAPINFOHEADER);
	bmif.biWidth         = m_tParam.nWidth;
	bmif.biHeight        = m_tParam.nHeigth;
	bmif.biPlanes        = 1;
	bmif.biBitCount      = 32;
	bmif.biCompression   = BI_RGB;
	bmif.biSizeImage     = m_tParam.nWidth * m_tParam.nHeigth * 4;
	bmif.biXPelsPerMeter = 0;
	bmif.biYPelsPerMeter = 0;
	bmif.biClrUsed       = 0;
	bmif.biClrImportant  = 0;

	m_hBitmap = CreateDIBSection(m_hMenDc, (LPBITMAPINFO)&bmif, DIB_RGB_COLORS, &m_lpData, NULL, NULL);
	if (m_lpData == NULL)
		m_bInit = false;
	else
		m_bInit = true;

	m_nBuffLen = m_tParam.nWidth * m_tParam.nHeigth * 4;

	m_pData = new char[m_nBuffLen];

	return m_bInit;
}

void CScreenCapture::CaptureScreen(void)
{
	HDC dc = GetDC(NULL);
	if (dc == NULL)
		return;
	
	SelectObject(m_hMenDc, m_hBitmap);

	BitBlt(m_hMenDc, 0, 0, m_tParam.nWidth, m_tParam.nHeigth, dc, 0, 0, SRCCOPY);

	long lLen = GetBitmapBits(m_hBitmap, m_nBuffLen, m_pData);

	if (m_pNotify)
	{
		m_pNotify->OnCaptureNotify(m_pData, m_nBuffLen, &m_tParam);		

		memset(m_pData, 0x00, m_nBuffLen);
	}

	DeleteDC(dc);
}
